<!--
 * @Description:
 * @Author: 崔堂袁
 * @Date: 2021-04-16 18:44:24
 * @LastEditTime: 2021-05-11 12:28:25
-->
<template>
  <div class="homeHeader">
    <!-- 左边标题 -->
    <div class="header-title"><span>{{$t('lang.home.myAchievements')}}</span></div>
    <!-- 语言选择器 -->
    <a-select :default-value="locale"
              style="width: 100px; margin-right: 50px;"
              @change="changeLanguage">
      <a-select-option value="ch">中文</a-select-option>
      <a-select-option value="en">English</a-select-option>
    </a-select>
    <!-- 主题选择器 -->
    <a-dropdown :trigger="['click']">
      <a class="ant-dropdown-link-theme"
         @click.prevent>
        <img :src="themeIconSrc">
      </a>
      <template #overlay>
        <a-menu>
          <a-menu-item>
            <a @click="changeTheme('blue', '#1296db')">{{$t('lang.home.tiankongLan')}}</a>
          </a-menu-item>
          <a-menu-item>
            <a @click="changeTheme('gray', '#8a8a8a')">{{$t('lang.home.naiNaiHui')}}</a>
          </a-menu-item>
          <a-menu-item>
            <a @click="changeTheme('green', '#4edd35')">{{$t('lang.home.qingXinLv')}}</a>
          </a-menu-item>
          <a-menu-item>
            <a @click="changeTheme('orange', '#e98f36')">{{$t('lang.home.jinJuJu')}}</a>
          </a-menu-item>
          <a-menu-item>
            <a @click="changeTheme('pink', '#fd88af')">{{$t('lang.home.jiangZi')}}</a>
          </a-menu-item>
        </a-menu>
      </template>
    </a-dropdown>
    <!-- 新建设计按钮 -->
    <a-button @click="toNewDesign">{{ $t('lang.home.newScene')}}</a-button>
    <!-- 用户信息 -->
    <a-dropdown>
      <a class="ant-dropdown-link"
         @click.prevent>
        <div class="userInformations">
          <div class="avatar">
            <UserOutlined />
          </div>
          <div class="userName">
            <a>{{userName}}</a>
          </div>
        </div>
      </a>
      <template #overlay>
        <a-menu>
          <a-menu-item>
            <a @click="userListClick">{{$t('lang.home.updateUserName')}}</a>
          </a-menu-item>
          <a-menu-item>
            <a @click="changePassword">{{$t('lang.home.changePassword')}}</a>
          </a-menu-item>
          <a-menu-item>
            <a @click="exit">{{$t('lang.home.exit')}}</a>
          </a-menu-item>
        </a-menu>
      </template>
    </a-dropdown>
    <a-modal class="userModal"
             v-model:visible="showModal"
             :title="$t('lang.home.updateUserName')"
             :okText="$t('lang.home.update')"
             :cancelText="$t('lang.home.cancel')"
             @ok="updateUserNameHandleOk">
      <a-spin :spinning="spinning">
        <div class="userName">
          <div class="title">{{$t('lang.home.newUserName')}}：</div>
          <div class="input">
            <a-input :placeholder="$t('lang.home.newUserName')"
                     v-model:value="newUserName">
              <template #suffix>
                <CloseCircleOutlined @click="clearNewUserName" />
              </template>
            </a-input>
          </div>
        </div>
      </a-spin>
    </a-modal>
    <a-modal class="exitModal"
             v-model:visible="showExitModal"
             :title="$t('lang.home.exitModalTitle')"
             :okText="$t('lang.home.ok')"
             :cancelText="$t('lang.home.cancel')"
             @ok="exitHandleOk">
      {{$t('lang.home.exitText')}}
    </a-modal>
    <a-modal class="changePasswordModal"
             v-model:visible="showChangePasswordModal"
             :title="$t('lang.home.changePassword')"
             :okText="$t('lang.home.update')"
             :cancelText="$t('lang.home.cancel')"
             @ok="changePasswordHandleOk">
      <a-spin :spinning="spinning">
        <div class="changePassword">
          <div class="password">
            <div class="title">{{$t('lang.home.inputOldPasswordTitle')}}</div>
            <div class="input">
              <a-input-password :placeholder="$t('lang.home.inputOldPasswordTitle')"
                                type="password"
                                v-model:value.lazy="oldPassword">
                <template #prefix>
                  <UnlockOutlined />
                </template>
              </a-input-password>
            </div>
          </div>
          <div class="password">
            <div class="title">{{$t('lang.home.inputNewPassWordTitle')}}</div>
            <div class="input">
              <a-input-password :placeholder="$t('lang.home.inputNewPassWordTitle')"
                                type="password"
                                v-model:value.lazy="newPassword">
                <template #prefix>
                  <UnlockOutlined />
                </template>
              </a-input-password>
            </div>
          </div>
          <div class="password">
            <div class="title">{{$t('lang.home.confirmNewPasswordTitle')}}</div>
            <div class="input">
              <a-input-password :placeholder="$t('lang.home.confirmNewPasswordTitle')"
                                type="password"
                                v-model:value.lazy="newPassword2">
                <template #prefix>
                  <UnlockOutlined />
                </template>
              </a-input-password>
            </div>
          </div>
        </div>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
import { useI18n } from 'vue-i18n'
import { reactive, toRefs, computed, onMounted, ref, getCurrentInstance } from 'vue'
import { UserOutlined, CloseCircleOutlined, UnlockOutlined } from '@ant-design/icons-vue'

import { useStore } from 'vuex'
import { message } from 'ant-design-vue'
export default {
  components: {
    UserOutlined,
    CloseCircleOutlined,
    UnlockOutlined
  },
  setup () {
    // -------------------------------mounted----------------------------------
    const userName = ref('')
    onMounted(() => {
      // 验证是否登录
      if (sessionStorage.getItem('loginState')) { // 已经登录
        const currentUserName = sessionStorage.getItem('userName')
        const currentUserAccount = sessionStorage.getItem('userAccount')
        if (currentUserName !== 'null') {
          userName.value = currentUserName
        } else {
          userName.value = currentUserAccount
        }
      } else { // 没有登录，回到欢迎界面
        proxy.$router.push('/welcome')
      }
    })

    // --------------------------语言选择--------------------------
    const { locale } = useI18n()
    locale.value = 'ch'
    function changeLanguage (value) {
      localStorage.setItem('language', value)
      locale.value = localStorage.getItem('language')
    }
    if (localStorage.getItem('language')) locale.value = localStorage.getItem('language')

    // --------------------------主题切换---------------------------
    const store = useStore()
    const themeData = reactive({
      themeColors: {
        theme_blue: { // 蓝色
          baseColor: '#409EFF',
          activeColor: '#AACDF1',
          fontColor: '#0E6FD3'
        },
        theme_gray: { // 灰色
          baseColor: '#909399',
          activeColor: '#CBCED5',
          fontColor: '#787C82'
        },
        theme_green: { // 绿色
          baseColor: '#67D631',
          activeColor: '#DDF7D1',
          fontColor: '#39B400'
        },
        theme_orange: { // 橙色
          baseColor: '#F8AA36',
          activeColor: '#FED8A0',
          fontColor: '#DC8406'
        },
        theme_pink: { // 粉红色
          baseColor: '#F56C6C',
          activeColor: '#F7E4E4',
          fontColor: '#CF6A6A'
        }
      }
    })
    // 选中某一个主题颜色后触发
    const changeTheme = (color, primaryColor) => {
      localStorage.setItem('userThemeColor', color)
      localStorage.setItem('antdPrimaryColor', primaryColor)
      changeThemeSrc(require(`@/assets/themeIcons/theme-${color}.png`))
      changeAntdPrimaryColor(primaryColor)
      changeLessColor(color)
    }

    // 修改vuex中主题图标路径
    const changeThemeSrc = (newSrc) => store.commit('themeColorControl/changeThemeIconSrc', newSrc)
    // 改变antd组件颜色主题
    const changeAntdPrimaryColor = primaryColor => {
      window.less.modifyVars({
        '@primary-color': primaryColor
      })
    }
    // 改变less变量颜色值
    const changeLessColor = color => {
      const colorName = `theme_${color}`
      document.getElementsByTagName('body')[0].style.setProperty('--baseColor', themeData.themeColors[colorName].baseColor)
      document.getElementsByTagName('body')[0].style.setProperty('--activeColor', themeData.themeColors[colorName].activeColor)
      document.getElementsByTagName('body')[0].style.setProperty('--fontColor', themeData.themeColors[colorName].fontColor)
      localStorage.setItem('baseColor', themeData.themeColors[colorName].baseColor)
      localStorage.setItem('activeColor', themeData.themeColors[colorName].activeColor)
      localStorage.setItem('fontColor', themeData.themeColors[colorName].fontColor)
    }

    // ------------------------------点击新建场景跳转路由-----------------------
    const { proxy } = getCurrentInstance()
    const toNewDesign = () => {
      proxy.$router.push({ path: '/newDesign' })
    }
    // ------------------------------点击用户信息列表------------------------------
    const showModal = ref(false)
    const newUserName = ref('')
    const spinning = ref(false)
    const userListClick = () => {
      showModal.value = true
    }
    const clearNewUserName = () => {
      newUserName.value = ''
    }
    const updateUserNameHandleOk = () => {
      spinning.value = true
      proxy.$http.post('/api/user/updateUserName', { newUserName: newUserName.value, userAccount: sessionStorage.getItem('userAccount') })
        .then((res) => {
          if (res.data === 'success') {
            message.success(proxy.$t('lang.home.updateSuccess'))
            userName.value = newUserName.value
            sessionStorage.setItem('userName', newUserName.value)
            showModal.value = false
            spinning.value = false
          }
        })
    }

    // --------------修改密码---------------
    const oldPassword = ref('')
    const newPassword = ref('')
    const newPassword2 = ref('')
    const showChangePasswordModal = ref(false)
    const changePassword = () => {
      showChangePasswordModal.value = true
    }
    const changePasswordHandleOk = () => {
      if (!newPassword.value) { // 密码不能为空
        message.error(proxy.$t('lang.registerModal.nullPassword'))
        return
      }
      if (newPassword.value !== newPassword2.value) { // 密码不一致
        message.error(proxy.$t('lang.registerModal.differentPassword'))
        return
      }
      const userAccount = sessionStorage.getItem('userAccount')
      const data = {
        userAccount,
        oldPassword: oldPassword.value,
        newPassword: newPassword.value
      }
      spinning.value = true
      proxy.$http.post('/api/user/updatePassword/find', data)
        .then((res) => {
          const result = res.data
          if (result === 'errorPassword') {
            message.error(proxy.$t('lang.home.errorOldPassword'))
            spinning.value = false
          } else if (result === 'allowUpdatePassword') {
            updatePassword(data)
          }
        })
    }
    const updatePassword = (data) => {
      proxy.$http.post('/api/user/updatePassword', data)
        .then((res) => {
          if (res.data === 'success') {
            message.success(proxy.$t('lang.home.updatePasswordSuccess'))
            spinning.value = false
          }
        })
    }
    // --------------退出登录---------------
    const showExitModal = ref(false)
    const exit = () => {
      showExitModal.value = true
    }
    const exitHandleOk = () => {
      proxy.$router.push('/welcome')
    }

    return {
      changeLanguage,
      locale,
      ...toRefs(themeData),
      themeIconSrc: computed(() => store.state.themeColorControl.themeIconSrc),
      changeTheme,
      toNewDesign,
      userName,
      userListClick,
      showModal,
      newUserName,
      clearNewUserName,
      updateUserNameHandleOk,
      exit,
      showExitModal,
      exitHandleOk,
      changePassword,
      showChangePasswordModal,
      changePasswordHandleOk,
      oldPassword,
      newPassword,
      newPassword2,
      spinning
    }
  }
}
</script>

<style lang='less' scoped>
.homeHeader {
  width: 100%;
  height: 46px;
  border-bottom: 1px solid @activeColor;
  box-shadow: 0px 5px 5px @activeColor;
  display: flex;
  align-items: center;
  padding: 0 20px;
  position: relative;
  .header-title {
    width: 200px;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: @fontColor;
    span {
      font-family: inter;
      font-size: 18px;
    }
  }
  .ant-select {
    color: @fontColor;
  }
  .ant-dropdown-link-theme {
    img {
      width: 30px;
      height: 30px;
    }
  }
  .ant-btn {
    color: @fontColor;
    border-radius: 4px;
    margin-left: 50px;
  }
  .ant-dropdown-link {
    margin-left: auto;
    .userInformations {
      display: flex;
      align-content: center;
      cursor: pointer;
      .avatar {
        display: inline-block;
        width: 30px;
        height: 30px;
        background-color: @activeColor;
        border: 1px solid @baseColor;
        border-radius: 50%;
        text-align: center;
        line-height: 30px;
        font-size: 20px;
      }
      .userName {
        width: auto;
        height: 30px;
        display: inline-block;
        margin-left: 10px;
        line-height: 30px;
        a {
          color: @fontColor;
        }
      }
    }
  }
}
</style>

<style lang='less'>
.userModal {
  .userName {
    display: flex;
    justify-content: center;
    align-content: center;
    .title {
      text-align: end;
      line-height: 32px;
    }
    .ant-input-suffix {
      color: @activeColor;
      &:hover {
        cursor: pointer;
        color: @baseColor;
      }
    }
  }
}
.changePasswordModal {
  .changePassword {
    display: flex;
    flex-direction: column;
    .password {
      width: 100%;
      height: 40px;
      display: flex;
      align-items: center;
      .title {
        flex: 1;
        text-align: end;
        padding: 0 10px;
      }
      .input {
        flex: 2;
        padding: 0 30px 0 0;
        .ant-input-suffix {
          color: @activeColor;
          &:hover {
            cursor: pointer;
            color: @baseColor;
          }
        }
      }
    }
  }
}
</style>
